﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Chowpoo.Common;
using Chowpoo.Util;
using CourseSystem.Common.Helpers;
using CourseSystem.Common.Models;
using CourseSystem.Core.BLL;
using CourseSystem.Core.Enum;
using CourseSystem.Core.Entities;

namespace CourseSystem.Web.Controllers
{
    public class AccountController : Controller
    {
        public ActionResult Logon()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Logon(LogOnModel info)
        {
            if (!ModelState.IsValid)
            {
                ViewData["AlertMsg"] = "登录失败.";
                return View();
            }
            //执行学生学号登录流程
            if (CommonUtils.IsInt(info.Account))
            {
                var user = StudentBLL.Login(info.Account, Security.Pass2Md5(info.PassWord));
                if (user != null)
                {
                    if ((RegReviewEnum)user.RegType != RegReviewEnum.Pass)
                    {
                        ViewData["AlertMsg"] = "注册未通过审核,请联系老师.";
                        return View();
                    }
                    user.LearnTimes++;
                    user.LastIp = CommonRequest.GetIP();
                    StudentBLL.Edit(user);
                    UserHelper.SetLogined(new UserModel { Id = user.Id, UserName = user.StuName, UserType = UserTypeEnum.Student });
                    return RedirectToAction("Index", "Home");
                }
                ViewData["AlertMsg"] = "登录失败.";
                return View();
            }
            var teacher = TeacherBLL.Login(info.Account, Security.Pass2Md5(info.PassWord));
            if (teacher != null)
            {
                UserHelper.SetLogined(new UserModel { Id = teacher.Id, UserName = teacher.Name, UserType = teacher.IsAdmin ? UserTypeEnum.Admin : UserTypeEnum.Teacher });
                return RedirectToAction("Index", "Admin");
            }
            ViewData["AlertMsg"] = "登录失败.";
            return View();
        }

        public ActionResult RegUc()
        {
            ViewData.Model = new StudentInfo();
            return PartialView();
        }

        [HttpPost]
        public ActionResult RegUc(StudentInfo info)
        {
            if (!ModelState.IsValid)
            {
                return PartialView();
            }
            ViewData["msg"] = "注册成功!请等待审核...";
            ViewData.Model = new StudentInfo();
            return PartialView();
        }

        public ActionResult GuessLogin()
        {
            UserHelper.SetLogined(new GuessModel());
            return RedirectToAction("Index", "Home");
        }
    }
}
